package com.business.controller;

import com.business.bean.ClusterInfo;
import com.business.bean.TreeNode;
import com.business.services.QueryServer;
import com.business.util.DerbyConn;
import com.business.util.HelpMe;
import com.business.util.TouchJdbc;
import com.business.util.ZkClient;
import com.google.common.collect.Lists;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by mengdexuan on 2017/1/15 13:23.
 */
@Controller
public class IndexController{

	private static org.slf4j.Logger log= LoggerFactory.getLogger(IndexController.class);
	private TouchJdbc touchJdbc = TouchJdbc.getInstance();
	@Autowired
	private QueryServer queryServer;
	



	@RequestMapping("/")
	public String index(HttpServletRequest request, Model model) throws Exception {
		log.info("主页面……");

		List<ClusterInfo> clusterInfoList = queryServer.listCluster();

		model.addAttribute("list",clusterInfoList);

		return "index";
	}



	//清空 ZK 连接
	@RequestMapping("/clearConn")
	@ResponseBody
	public String clearConn(){
		ZkClient.clearConn();
		log.info("清空 ZK 连接！");
		return "ok";
	}

	@RequestMapping("/addServer")
	@ResponseBody
	public String addServer(@RequestParam Map<String,Object> map) throws Exception {


		String ip = HelpMe.getStrFromMap("ip",map);
		int port = HelpMe.getIntFromMap("port",map);

		if (HelpMe.isNull(ip)){
			return "error";
		}

		log.info("ip --> "+ip+"		port --> "+port);

		boolean flag = queryServer.addServer(ip, port);

		log.info("添加服务结果："+flag);

		return "ok";
	}


	@RequestMapping("/delServer")
	@ResponseBody
	public String delServer(@RequestParam String uuid){
		try {
			touchJdbc.update(DerbyConn.getConn(),"delete from server_info where uuid = '"+uuid+"'");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "ok";
	}

	@RequestMapping("/data")
	@ResponseBody
	public TreeNode[] data(@RequestParam String clusterId) throws Exception {

		log.info("clusterId --> "+clusterId);

		TreeNode node = queryServer.getNode(clusterId);

		return new TreeNode[]{node};
	}


	@RequestMapping("/delAllNode")
	@ResponseBody
	public String delAllNode(@RequestParam String clusterId) throws Exception {
		log.info("clusterId --> "+clusterId);

		queryServer.deleteAllNode(clusterId,"/");
		return "ok";
	}

	@RequestMapping("/toManager")
	public String toManager(){
		return "manager";
	}


	@RequestMapping("/getNodes")
	public String getNodes(@RequestParam String clusterId,Model model)throws Exception{

		model.addAttribute("clusterId",clusterId);


		String clusterName = queryServer.getClusterName(clusterId);

		model.addAttribute("clusterName",clusterName);


		log.info("clusterName --> "+clusterName);

		return "node";
	}


	@RequestMapping("/clusterData")
	@ResponseBody
	public List<Map<String, Object>> clusterData(){

		List<Map<String, Object>> mapList = queryServer.clusterData();
		mapList = HelpMe.swapMapKeyCase(mapList);

		if (HelpMe.isNull(mapList)){
			return new ArrayList<Map<String, Object>>();
		}
		return mapList;
	}

	@RequestMapping("/getData")
	@ResponseBody
	public Map<String, Object> getData(@RequestParam Map<String,Object> paramMap) throws Exception {

		String uuid = HelpMe.getStrFromMap("uuid",paramMap);
		int type = HelpMe.getIntFromMap("type",paramMap);

		Map<String, Object> map = queryServer.getData(type, uuid);

		return map;
	}

	@RequestMapping("/serverData")
	@ResponseBody
	public List<Map<String, Object>> serverData(){

		List<Map<String, Object>> mapList = queryServer.serverData();
		mapList = HelpMe.swapMapKeyCase(mapList);

		if (HelpMe.isNull(mapList)){
			return new ArrayList<Map<String, Object>>();
		}
		return mapList;
	}



	@RequestMapping("/addOrEditData")
	@ResponseBody
	public String addOrEditData(@RequestParam Map<String, Object> map) throws Exception {
		int flag = HelpMe.getIntFromMap("flag",map);
		boolean isAdd = Boolean.parseBoolean(HelpMe.getStrFromMap("isAdd",map));
		if (flag==1){
			String uuid = null;
			if (!isAdd){
				uuid = HelpMe.getStrFromMap("uuid",map);
			}
			String name = HelpMe.getStrFromMap("name",map);
			if (HelpMe.isNull(name)){
				return "error";
			}
			queryServer.addData(name,uuid);
		}else if (flag==2){
			String ip = HelpMe.getStrFromMap("ip",map);
			Integer port = HelpMe.getIntFromMap("port",map);
			String cluster = HelpMe.getStrFromMap("cluster",map);
			String uuid = null;
			if (!isAdd){
				uuid = HelpMe.getStrFromMap("uuid",map);
			}
			if (HelpMe.isNull(ip)||port==null){
				return "error";
			}
			queryServer.addData(ip,port,cluster,uuid);
		}

		return "ok";
	}




	@RequestMapping("/delData")
	@ResponseBody
	public String delData(@RequestParam Map<String,Object> map) throws Exception {
		int flag = HelpMe.getIntFromMap("flag",map);
		String uuid = HelpMe.getStrFromMap("uuid",map);

		boolean success = queryServer.delData(flag,uuid);

		return success+"";
	}


	@RequestMapping("/getServerByClusterId")
	@ResponseBody
	public List<List<Map<String, Object>>> getServerByClusterId(@RequestParam String uuid){
		List<Map<String, Object>> mapList = queryServer.getServerByClusterId(uuid);

		mapList = HelpMe.swapMapKeyCase(mapList);

		if (HelpMe.isNull(mapList)){
			return new ArrayList<>();
		}

		//每 3 个切分成一个单独的 List
		List<List<Map<String, Object>>> result = Lists.partition(mapList, 3);

		return result;
	}







	//=========================================   以下是 ZK 节点操作方法 ===============================================

	//创建 ZK 节点
	@RequestMapping("/addZkNode")
	@ResponseBody
	public String addZkNode(@RequestParam Map<String,Object> map)throws Exception {

		String clusterId = HelpMe.getStrFromMap("clusterId",map);
		String path = HelpMe.getStrFromMap("path",map);
		String pathVal = HelpMe.getStrFromMap("pathVal",map);

		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		if (HelpMe.isNull(pathVal)){
			zooKeeper.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}else {
			zooKeeper.create(path, pathVal.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}
		log.info("创建 ZK 节点：path --> "+path+"	val --> "+pathVal);
		return "ok";
	}



	//查询 ZK 节点数据
	@RequestMapping("/getZkNodeData")
	@ResponseBody
	public String getZkNodeData(@RequestParam Map<String,Object> map)throws Exception {

		String clusterId = HelpMe.getStrFromMap("clusterId",map);
		String path = HelpMe.getStrFromMap("path",map);

		String val = "";
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		byte[] data = zooKeeper.getData(path, false, null);
		if (data!=null){
			val = new String(data);
		}

		return val;
	}


	//删除 ZK 节点
	@RequestMapping("/delZkNode")
	@ResponseBody
	public String delZkNode(@RequestParam Map<String,Object> map)throws Exception {
		String clusterId = HelpMe.getStrFromMap("clusterId",map);
		String path = HelpMe.getStrFromMap("path",map);
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);

		TreeNode node = queryServer.listChildren(clusterId, path);

		delNode(clusterId,node);

		return "ok";
	}


	//级联删除 ZK 节点
	public void delNode(String clusterId,TreeNode node) throws Exception{
		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		TreeNode[] children = node.getChildren();
		if (HelpMe.isNotNull(children)){
			for (TreeNode temp:children){
				delNode(clusterId,temp);
			}
		}
		zooKeeper.delete(node.getName(), -1);
		log.info("删除 ZK 节点：path --> "+node.getName());
	}



	//更新 ZK 节点数据
	@RequestMapping("/updateZkNode")
	@ResponseBody
	public String updateZkNode(@RequestParam Map<String,Object> map)throws Exception {

		String clusterId = HelpMe.getStrFromMap("clusterId",map);
		String path = HelpMe.getStrFromMap("path",map);
		String pathVal = HelpMe.getStrFromMap("pathVal",map);

		ZooKeeper zooKeeper = ZkClient.getZk(clusterId);
		if (HelpMe.isNull(pathVal)){
			zooKeeper.setData(path,null,-1);
		}else {
			zooKeeper.setData(path,pathVal.getBytes(),-1);
		}
		log.info("更新 ZK 节点数据：path --> "+path+"		val --> "+pathVal);
		return "ok";
	}




}
